package zilvic.game.room.entity.trigger;

import zilvic.resources.ByteMagic;
import zilvic.resources.Parsable;

/**
 *
 * @author Duncan
 */
public class Timer implements Parsable {
    private long timeLeft;
    private Action action;

    public Timer(long timeLeft, Action action) {
        this.timeLeft = timeLeft;
        this.action   = action;
    }

    /**
     * Is called each step by the room. If the timer returns true then it is
     * done and should be removed from the room.
     * @param delta The delta time since the last tick.
     * @return True if the timer should be removed. Else false.
     */
    public boolean tick(long delta) {
        timeLeft -= delta;
        if (timeLeft < 0) {
            if (action != null)
                action.onAction();
            return true;
        }
        return false;
    }

    public void setTimeLeft(long timeLeft) {
        this.timeLeft = timeLeft;
    }

    public void detonate() {
        timeLeft = -1;
    }

    /**
     * The format is as follows.
     * 0:  The timeLeft (long).
     * 1:  The action-name. (String).
     * @return This effect in bytes.
     */
    public byte[] toBytes() {
        return ByteMagic.compressBytes(new byte[][] {
            ByteMagic.longToBytes(timeLeft),
            action.getName().getBytes()});
    }

    public void fromBytes(byte[] bytes) {
        byte[][] u = ByteMagic.uncompressBytes(bytes);
        timeLeft = ByteMagic.bytesToLong(u[0]);
        ActionStore.get().get(ByteMagic.bytesToString(u[1]));
    }
}
